/*
 * ********************************************************************************
 * Project:        GAMES, 7th Framework Programme, co-funded by European Commission
 * Product:        ESMI Prototype
 * File:           NumericTextField.java (UTF-8)
 * Created by:     Alessandro Rossi <alessandro.rossi@eng.it>
 * Created on:     13-dic-2011 2.44.37
 * 
 * (C) Copyright 2010-2012 Engineering Ingegneria Informatica S.p.A.
 * 
 * This file is part of the Energy Sensing & Monitoring Infrastructure of GAMES.
 * ********************************************************************************
 * 
 * The terms of the license are under discussion and will be defined.
 * Until then, the distribution of this file is restricted to the members of the GAMES Consortium.
 */
package eu.games.esmi.ieat.indicatorrelations.ui;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;

/**
 *
 * @author Alessandro
 */
@SuppressWarnings("serial")
public class NumericTextField extends HorizontalLayout implements
        ValueChangeListener {

    private TextField integer;

    public Integer getNumber() {
        Object value = integer.getValue();
        if (!isInteger(value)) {
            return null;
        } else {
            return Integer.parseInt(value.toString());
        }
    }

    public NumericTextField(String caption) {
        this(caption, null);
    }

    public NumericTextField(String caption, Integer initialValue) {
        setSpacing(true);
        
        integer = new TextField(caption);
        integer.setInputPrompt("Set interval");

        if (initialValue != null) {
            integer.setValue(initialValue);
        }
        integer.setImmediate(true);

        // Add valuechangelistener
        integer.addListener(this);
        integer.setImmediate(true);

        addComponent(integer);
    }

    public void valueChange(ValueChangeEvent event) {
        // Get the new value and format it to the current locale
        Object value = event.getProperty().getValue();
        if (!isInteger(value)) {
            getWindow().showNotification("Integer value required");
            integer.setValue(5000);
        } else {
            // Show notification
            getWindow().showNotification("Interval set to: " + value);
        }
    }

    private boolean isInteger(Object o) {
        try {
            Integer.parseInt(o.toString());
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
